# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from PyQt5.QtCore import QPoint, Qt, QCoreApplication, pyqtSlot
from PyQt5.QtGui import  QBrush, QPixmap, QColor, QPainter,QIcon,QPolygon
from PyQt5.QtWidgets import (QAction, QColorDialog, QComboBox, QDialog, QFontDialog,
                               QGroupBox, QHBoxLayout, QMainWindow, QLabel,
                               QLineEdit, QMessageBox, QPushButton, QToolBar,
                               QTableWidgetItem, QTableWidget, QVBoxLayout, QWidget)
from PyQt5.QtCore import pyqtSignal
from PyQt5 import QtWidgets
import logging
from spreadsheetdelegate import SpreadSheetDelegate
from delegates import PixmapDelegate
class MyTableWidget(QTableWidget):
    dragbottom = pyqtSignal(object)
    def __init__(self,parent):
        super().__init__(parent)
        self.cellBottomRight=False
        self.leftbuttonDown=False
    def paintEvent(self,e):
        super().paintEvent(e)
        painter=QPainter(self.viewport())
        # painter.save();
        pen = painter.pen();
        pen.setWidth(1);
        selections = self.selectionModel()
        if selections!=None:
            # logging.info("not None")
            list1 = selections.selectedIndexes()
            for i in range(len(list1)):
                modelIndex = list1[i]
                #QRect类提供各种矩形坐标，绘制线跟点的时候需要用到坐标
                rect = self.visualRect(modelIndex);
                tmpRect=QtCore.QRect(QtCore.QPoint(rect.x()+1,rect.y()+1),QtCore.QSize(rect.width()-2,rect.height()-2))
     
                #如果是选中状态 并且在选择公式状态
                # if (self.item(i,j).isSelected()):
                #给选中单元格进行画线画点
                dashes=[]
                penXu = painter.pen();
                #设置画笔宽度
                penXu.setWidth(2);
                color=QColor();
                #设置画笔颜色
                color.setRgb(31,187,125);
                penXu.setColor(color);
                painter.setPen(penXu);
                #绘制单元格四周的线
                painter.drawRect(tmpRect);
                #绘制单元格右下角点
                penXu.setWidth(6);
                painter.setPen(penXu);
                painter.drawPoint(tmpRect.x()+tmpRect.width() -3,tmpRect.y()+tmpRect.height()-3);
        #恢复QPainter对象
        # painter.restore();
        # self.viewport().update();
    #鼠标移动事件
    def mouseMoveEvent(self,event):
        #获取鼠标位置信息
        if not self.cellBottomRight:
            mousePos =event.pos();
            #获取所有选中单元格
            # logging.info(self.cellBottomRight)
            itemList = self.selectedItems();
            #没有选中单元格 就退出
            if len(itemList) <= 0:
                return;
            modelIndex = self.indexFromItem(itemList[len(itemList)-1]);
            #获取最后一个选中的单元格的QRect，用来判断是否鼠标位置是否在右下角区域
            rect = self.visualRect(modelIndex);
            # logging.info([mousePos,rect])
            #判断是否在我们规定的区域，或者是按下模式，isClick是按下模式标志
            # print(dir(mousePos))
            if((mousePos.x() >= (rect.x()+rect.width() -7) and mousePos.x() <= (rect.x()+rect.width())
                and mousePos.y() >= (rect.y()+rect.height()-7) and mousePos.y() <= (rect.y()+rect.height()))):
                # logging.info("right bottom")
                #设置鼠标在右下角区域样式
                self.setCursor(Qt.CrossCursor);
                #在右下角区域
                self.cellBottomRight = True;
        super().mouseMoveEvent(event);
        #鼠标点击事件
    def mousePressEvent(self,event):
        if(event.button()==Qt.LeftButton):
            self.leftbuttonDown = True;
            self.setCursor(Qt.SizeAllCursor);
        else:
            self.leftbuttonDown = False;
            self.setCursor(Qt.ArrowCursor);
        super().mousePressEvent(event);#提交鼠标给控件
    def mouseReleaseEvent(self,ev):
        if self.leftbuttonDown and self.cellBottomRight:
            itemList = self.selectedItems();
            if len(itemList)>0:
                logging.info("dragbottom")
                self.dragbottom.emit(itemList)
        self.leftbuttonDown = False;
        self.cellBottomRight = False;
        self.setCursor(Qt.ArrowCursor);
        super().mouseReleaseEvent(ev)
class BiaoYe():
    def __init__(self):
        self.V1=""
        self.V3=""
        self.V4=""
        self.V5=""
        self.V6=""
        self.V7=""
        self.c=""
class BiaoYeTableWidget(MyTableWidget):
    def __init__(self,parent):
        super().__init__(parent)
        # self.setItemDelegate(PixmapDelegate())
        self.properties = [
            {"ele":None,"delegate":"floatEdit",'width':130,'attr': "V1",'visible':True,  'header': "标准溶液体积V1"},
            {"ele":None,"delegate":"floatEdit",'width':80,'attr': "V3",'visible':True,  'header': "滴定体积V3"},
            {"ele":None,"delegate":"floatEdit",'width':80,'attr': "c",'visible':True,  'header': "滴定溶液浓度c"},
            {"ele":None,"delegate":"floatEdit",'width':130,'attr': "V4",'visible':True,  'header': "溶液体积V4"},
            {"ele":None,"delegate":"floatEdit",'width':80,'attr': "V5",'visible':True,  'header': "第一次滴定V5"},
            {"ele":None,"delegate":"floatEdit",'width':80,'attr': "V6",'visible':True,  'header': "第二次滴定V6"},
            {"ele":None,"delegate":"floatEdit",'width':80,'attr': "V7",'visible':True,  'header': "校正体积V7"},
        ]
        # logging.info(self.height())
        # self.height=1000
        self.resize(self.width(),100)
        self.objs=[]
        for i in range(3):
            one=BiaoYe()
            self.objs.append(one)
        self.objectsToGrid()
        self.itemChanged.connect(self.item_change)
    def item_change(self,item):
        print(item)
        # print(dir(item))
        row=item.row()
        col=item.column()
        v=item.text()
        obj=self.objs[row]
        setattr(obj,self.properties[col]["attr"],v) 
    def objectsToGrid(self):
        objs=self.objs
        self.blockSignals(True)
        rows=len(objs)
        cols=len(self.properties)
        self.setRowCount(rows)
        self.setColumnCount(cols)
        for i in range(cols):
            self.setHorizontalHeaderItem(i,QtWidgets.QTableWidgetItem(self.properties[i]["header"]))
            self.setColumnWidth(i,self.properties[i]["width"])
        i=0
        for one in objs:
            for j in range(cols):
                item=QtWidgets.QTableWidgetItem()
                if self.properties[j]["delegate"]!=None:
                    pass
                else:
                    item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled)
                v=getattr(one,self.properties[j]["attr"])
                # item.setText(str(v))
                item.setData(Qt.DisplayRole, v);
                self.setItem(i, j,item)
            i+=1 
        self.blockSignals(False)            
    pass        
